﻿
using System.IO.Ports;
using System.Net.Sockets;


namespace ModbusSlave.PortManager
{
    public class PortManager
    {
        public PortType portType { get; private set; } = PortType.Serial;

        public SerialPort serial { get; private set; }

        public TcpListener tcp { get; private set; }

        public UdpClient udp { get; private set; }


        public PortManager() 
        {
            serial = new SerialPort();
            tcp = new TcpListener(System.Net.IPAddress.Any, 502);
            udp = new UdpClient();
        }

        public void Connect(string name, int baurate, int datalen, StopBits stopBits, Parity parity)
        {
            portType = PortType.Serial;
        }

        public async Task Connect(int port)
        {
            portType = PortType.TCP;
            IsConnected = false;
            tcp = new TcpListener(System.Net.IPAddress.Any, port);

            await tcp.AcceptSocketAsync().ContinueWith(task =>
            {
                if (task.IsCompletedSuccessfully)
                {
                    IsConnected = true;
                }
            });
        }

        public void Connect(string ip, int port)
        {
            portType = PortType.UDP;
            udp.Connect(ip, port);
        }



        public void Disconnect()
        {

        }   

        public bool IsConnected { get; private set; }

    }
}
